package com.lanchetech.merchant.service.impl;


import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.baidu.fsg.uid.UidGenerator;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.bean.request.PageReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.CoinRewardResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.common.enums.DeletedEnum;
import com.lanchetech.common.enums.MsgUserRoleEnum;
import com.lanchetech.common.enums.MsgUserStatusEnum;
import com.lanchetech.common.enums.ResultCode;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.merchant.service.ServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ServiceServiceImpl implements ServiceService {

    @Resource
    UidGenerator uidGenerator;

    @Autowired
    MsgUserMapper msgUserMapper;

    @Autowired
    TenantMapper tenantMapper;

    @Autowired
    MerchantMapper merchantMapper;

    @Autowired
    MsgMapper msgMapper;

    @Autowired
    ShopMapper shopMapper;

    @Override
    public BaseResp editMsgUser(MsgUser msgUser) {
        MsgUser result = msgUserMapper.findOneByRelateIdAndRole(msgUser.getRelateId(), MsgUserRoleEnum.MERCHANT.getRole());

        if (msgUser.getId() == null) {
            // 一个人只能绑定一个账号
            if (result != null) {
                return new BaseResp(ResultCode.MSG_USER_USERNAME_EXISTS);
            }

            Merchant res = merchantMapper.selectByPrimaryKey(msgUser.getRelateId());
            if (res == null) {
                return new BaseResp(ResultCode.MERCHANT_NOT_EXISTS);
            }

            Merchant merchant = (Merchant) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Tenant tenant = tenantMapper.selectByPrimaryKey(merchant.getTenantId());
            Shop shop = shopMapper.selectByPrimaryKey(merchant.getTenantId());
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

            msgUserMapper.insert2(MsgUser.builder()
                    .username(Long.toString(uidGenerator.getUID()))
                    .password(encoder.encode(Long.toString(uidGenerator.getUID())))
                    .serviceName(msgUser.getServiceName())
                    .lastPasswordResetDate(new Date())
                    .status(msgUser.getStatus())
                    .relateId(msgUser.getRelateId())
                    .nickname(tenant.getTenantNickname())
                    .avatar(msgUser.getAvatar())
                    .role(MsgUserRoleEnum.MERCHANT.getRole())
                    .tenantId(shop.getId())
                    .createdAt(new Date())
                    .updatedAt(new Date())
                    .deleted(DeletedEnum.DEFAULT.getStatus())
                    .build());
        } else {
            // 如果绑定了新商家账号（新商家账号没有绑定其他客服账号），或者未修改商家账号，
            if (result == null || result.getId().equals(msgUser.getId())) {
                msgUser.setUpdatedAt(new Date());
                msgUserMapper.updateByPrimaryKeySelective(msgUser);
            }
        }

        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<MsgUser>> getMsgUserPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        req.setRole(MsgUserRoleEnum.MERCHANT.getRole());
        List<MsgUser> list = msgUserMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<MsgUser> getMsgUserDetail(Long id) {
        return new ResultData<>(msgUserMapper.selectByPrimaryKey(id));
    }

    @Override
    public BaseResp deleteMsgUser(Long id) {
        MsgUser msgUser = msgUserMapper.selectByPrimaryKey(id);
        msgUser.setRelateId(0 - msgUser.getId());
        msgUser.setStatus(MsgUserStatusEnum.OUT_SERVICE.getStatus());
        msgUser.setDeleted(DeletedEnum.DELETED.getStatus());
        msgUser.setUpdatedAt(new Date());
        msgUserMapper.updateByPrimaryKeySelective(msgUser);
        return new BaseResp();
    }

    @Override
    public ResultData<MsgUser> getPlatformMsgUser(Long msgUserId) {
        // 获取商家正在服务中的客服
        List<MsgUser> list = msgUserMapper.findAllByRoleAndStatusAndDeleted(MsgUserRoleEnum.ADMIN.getRole(), MsgUserStatusEnum.IN_SERVICE.getStatus(), DeletedEnum.DEFAULT.getStatus());
        if (!CollectionUtils.isEmpty(list)) {

            // 获取最近1次沟通的消息
            Msg msg = msgMapper.findOneLastByTenantIdAndFromId(0L, msgUserId);
            // 如果沟通过，并且还在3天内
            if (msg != null && msg.getCreatedAt().getTime() + 3 * 86400 * 1000 > System.currentTimeMillis()) {
                Optional<MsgUser> msgUserOptional = list.parallelStream().filter(s -> s.getId().equals(msg.getToId())).findFirst();
                // 如果在线
                if (msgUserOptional.isPresent()) {
                    return new ResultData<>(msgUserOptional.get());
                }
            }

            Random r = new Random();
            // 随机选择1个客服
            return new ResultData<>(list.get(r.nextInt(list.size())));
        }
        return new ResultData<>(null);
    }
}